const jwt = require('jsonwebtoken')
const { createUser, getUserInfo, updateById } = require('../service/user.service')
const { userRegisterError } = require('../consitan/err.type')
const { JWT_SECRET } = require('../config/config.default')
class UserController {
    async register(ctx, next) {
        // console.log(ctx.request.body)
        // 获取请求数据
        const { userName, passWord } = ctx.request.body
        try {
            // 操作数据库
            const res = await createUser(userName, passWord)
            ctx.body = {
                code: 0,
                message: '用户注册成功',
                result: {
                    id: res.id,
                    userName: res.userName
                }
            }
        } catch (err){
            console.log(err)
            ctx.app.emit('error', userRegisterError, ctx)
        }
    }
    async login(ctx, next) {
        const { userName } = ctx.request.body
        try {
            // resUser去除passWord后的参数对象
            const { passWord, ...resUser } = await getUserInfo({userName})
            const token = jwt.sign(resUser, JWT_SECRET, { expiresIn: '1d' })
            ctx.body = {
                code: 0,
                message: '用户登陆成功',
                result: {
                    token: token
                }
            }
        } catch (err) {
            console.error('用户登陆失败', err)
        }
    }
    async changePassword(ctx, next) {
        const id = ctx.state.user.id
        const passWord = ctx.request.body.passWord
        // console.log(id, passWord)
        if(await updateById({id, passWord})) {
            ctx.body = {
                code: 0,
                message: '密码修改成功',
                result: '',
            }
        }else {
            ctx.body = {
                code: '10007',
                message: '密码修改失败',
                result: ''
            }
        }
    }
}
module.exports = new UserController()